const { SOS } = window

// 初始化
export const InitLionKing = (sdk, api) => {
    console.log('初始化', sdk)
    api.info({ key: 'king', message: 'KING初始化...', placement: 'topLeft' })
    sdk.init()
        .then(() => {})
        .catch(err => api.error({ key: 'king', message: 'KING初始化失败', description: err, placement: 'topLeft' }))
    return sdk
}

// 销毁
export const DestructionKing = sdk => {
    sdk.destroy()
}

// SDK运行状态事件通知 Listener
export const SDK_STATE = (sdk, api, SDK_STATEEvent) => {
    sdk.addEventListener(SOS.EVENT.SDK_STATE, (event, code, description) => {
        switch (event) {
            case SOS.EVENT.SDK_STATE_CODE.WARN:
                api.info({
                    key: 'king',
                    message: '网络波动',
                    description: '一般是网络原因与服务器连接断开',
                    placement: 'topLeft',
                })
                break
            case SOS.EVENT.SDK_STATE_CODE.ERROR:
                if (code === SOS.ERROR_CODE.LOGIN_CONFLICT) {
                    // 账号在其他地方登录，这个需要处理下
                    api.info({
                        key: 'king',
                        message: '其他端登录',
                        description: '你的账号已在其他地方登录，你可以刷新一次，把对方挤下来',
                        placement: 'topLeft',
                    })
                    // 这里一定要记得把sdk destroy掉，不然会触发sdk的重连机制
                    sdk && sdk.destroy()
                    sdk = null
                }
                break
            case SOS.EVENT.SDK_STATE_CODE.SUCCESS:
                SOS.PERMISSION.getAudio()
                    .then(() => SDK_STATEEvent.emit(true))
                    .catch(err => {
                        SDK_STATEEvent.emit(false)
                    })
                break
            default:
                break
        }
    })
}

// 设备状态事件通知 Listener
export const DEVICE_STATE = sdk => {
    sdk.addEventListener(SOS.EVENT.DEVICE_STATE, (event, device) => {
        switch (event) {
            case SOS.EVENT.DEVICE_STATE_CODE.ONLINE:
                console.log('设备:', device.Id, device.Name, '上线')
                break
            case SOS.EVENT.DEVICE_STATE_CODE.OFFLINE:
                console.log('设备:', device.Id, device.Name, '离线')
                break
            default:
                break
        }
    })
}

//  设备告警事件通知 Listener
export const DEVICE_ALARM_STATE = (sdk, api, DEVICE_ALARM_STATEEvent) => {
    sdk.addEventListener(SOS.EVENT.DEVICE_ALARM_STATE, (event, device, task, operator) => {
        switch (event) {
            case SOS.EVENT.DEVICE_ALARM_STATE_CODE.RING:
                api.warning({ key: 'kingDEVICE', message: '告警信息...', placement: 'topLeft', duration: null })
                DEVICE_ALARM_STATEEvent.emit({
                    type: 'RING',
                    Id: device.Id,
                    TaskCode: task,
                })
                break
            case SOS.EVENT.DEVICE_ALARM_STATE_CODE.ACCEPT:
                // 本端sdk接警，也会有这个通知，需要判断出来是自己接的，还是其他人接的
                if (sdk.isMe(operator.SipNum)) {
                    api.success({ key: 'kingDEVICE', message: '已接警', placement: 'topLeft' })
                } else {
                    api.success({ key: 'kingDEVICE', message: '其他人接警', placement: 'topLeft' })
                    DEVICE_ALARM_STATEEvent.emit({ type: 'Close' })
                }
                break
            case SOS.EVENT.DEVICE_ALARM_STATE_CODE.NOANSWER:
                api.error({ key: 'kingDEVICE', message: '无人接警', placement: 'topLeft' })
                DEVICE_ALARM_STATEEvent.emit({ type: 'Close' })
                break
            case SOS.EVENT.DEVICE_ALARM_STATE_CODE.FINISHED:
                api.success({ key: 'kingDEVICE', message: '已完成接警', placement: 'topLeft' })
                DEVICE_ALARM_STATEEvent.emit({ type: 'Close' })
                break
            default:
                break
        }
    })
}

// 在线设备
export const deviceList = async (sdk, api, deviceListEvent) => {
    api.info({ key: 'kingList', message: '刷新在线列表...', placement: 'topLeft' })
    try {
        const res = await sdk.deviceList({
            PageSize: 100,
            PageNum: 1,
            Filters: [[{ Key: 'AppState', Type: 'str', Op: '=', Value: 'online' }]],
            OrderKey: 'OnlineTime',
            Desc: true,
        })
        console.log('获取设备列表成功', res)
        const data = res.RecordList.map(item => item.Id)
        deviceListEvent.emit(data)
        console.log('获取设备列表成功Id', data)
        api.success({ key: 'kingList', message: '在线列表已刷新', placement: 'topLeft' })
    } catch (err) {
        console.log('获取设备列表失败', err)
        api.error({ key: 'kingList', message: '获取在线设备失败', placement: 'topLeft' })
    }
}

// ! 开启
// 广播
export const microphoneMutilBoradcastStart = async ({ sdk, DeviceId, api, TaskCodeEvent }) => {
    api.info({ key: 'kingMic', message: '开启广播...', placement: 'topLeft' })
    try {
        const res = await sdk.microphoneMutilBoradcastStart({ DeviceIds: [DeviceId] })
        console.log('组建麦克风广播成功')
        TaskCodeEvent.emit({ type: 'kingMic', TaskCode: res.TaskCode })
        api.success({ key: 'kingMic', message: '广播成功', placement: 'topLeft' })
    } catch (error) {
        console.error('组建麦克风广播失败', error)
        api.error({ key: 'kingMic', message: '广播失败', placement: 'topLeft' })
    }
}

// 对讲
export const audioSpeakStart = ({ sdk, DeviceId, api, TaskCodeEvent }) => {
    const disconnectedCallback = SipNum => {
        console.warn(SipNum, '已退出对讲', sdk && sdk.isMe(SipNum))
    }
    api.info({ key: 'kingAudio', message: '开启对讲...', placement: 'topLeft' })
    sdk.audioSpeakStart({
        DeviceId,
        AudioDomId: 'html_audio_remote',
        SipNum: '400039900002321',
        Force: false,
        OnDisconnected: disconnectedCallback,
        OnStop: audioSpeakStop,
    })
        .then(res => {
            console.log('对讲成功')
            TaskCodeEvent.emit({ type: 'kingAudio', TaskCode: res.TaskCode })
            api.success({ key: 'kingAudio', message: '对讲成功.', placement: 'topLeft' })
        })
        .catch(e => {
            console.error('对讲失败:', e)
            api.error({ key: 'kingAudio', message: '对讲失败', description: e.message, placement: 'topLeft' })
        })
}

// 视频
export const videoMonitorStart = async ({ sdk, DeviceId, api, TaskCodeEvent }) => {
    api.info({ key: 'kingVideo', message: '开启视频...', placement: 'topLeft' })
    try {
        const res = await sdk.videoMonitorStart({
            DeviceId,
            VideoDomId: 'html_video_remote',
            OnStop: videoMonitorStop,
        })
        console.log('获取监控视频成功')
        TaskCodeEvent.emit({ type: 'kingVideo', TaskCode: res.TaskCode })
        api.success({ key: 'kingVideo', message: '视频成功', placement: 'topLeft' })
    } catch (e) {
        console.error('获取监控视频失败', e)
        api.error({ key: 'king', message: '视频失败', description: e.message, placement: 'topLeft' })
    }
}

// ! 停止
// 广播
export const microphoneMutilBoradcastStop = async (sdk, TaskCode, api, CloseEvent) => {
    api.info({ key: 'kingMic', message: '停止广播...', placement: 'topLeft' })
    try {
        await sdk.microphoneMutilBoradcastStop({ TaskCode })
        console.log('停止麦克风广播成功')
        CloseEvent.emit('kingMic')
        api.success({ key: 'kingMic', message: '停止广播成功', placement: 'topLeft' })
    } catch (error) {
        console.log('停止麦克风广播失败', error)
        api.error({ key: 'kingMic', message: '停止广播失败', placement: 'topLeft' })
    }
}

// 对讲
export const audioSpeakStop = async (sdk, TaskCode, api, CloseEvent) => {
    api.info({ key: 'kingAudio', message: '停止对讲...', placement: 'topLeft' })
    sdk.audioSpeakStop({ TaskCode })
        .then(() => {
            console.log('停止对讲成功')
            CloseEvent.emit('kingAudio')
            api.success({ key: 'kingAudio', message: '停止对讲成功', placement: 'topLeft' })
        })
        .catch(error => {
            console.error('停止对讲成功', error)
            api.error({ key: 'kingAudio', message: '停止对讲失败', placement: 'topLeft' })
        })
}

// 视频
export const videoMonitorStop = async (sdk, TaskCode, api, CloseEvent) => {
    api.info({ key: 'kingVideo', message: '停止视频...', placement: 'topLeft' })
    try {
        await sdk.videoMonitorStop({ TaskCode })
        console.log('停止监控视频成功')
        CloseEvent.emit('kingVideo')
        api.success({ key: 'kingVideo', message: '停止视频成功', placement: 'topLeft' })
    } catch (error) {
        console.log('停止监控视频失败', error)
        api.error({ key: 'kingVideo', message: '停止视频失败', placement: 'topLeft' })
    }
}

// !  接警
export const disconnectedCallback = async (sdk, alarmTaskObject, api) => {
    api.info({ key: 'kingDEVICE', message: '接警...', placement: 'topLeft' })
    try {
        const disconnectedCallback = SipNum => {
            console.warn(SipNum, '已退出接警', sdk && sdk.isMe(SipNum))
        }
        const rsp = await sdk.deviceAlarmAccept(alarmTaskObject, {
            AudioDomId: 'html_audio_remote',
            OnDisconnected: disconnectedCallback,
            OnStop: deviceAlarmDone,
        })
        console.log('接警成功, expire（接警时间，单位秒）:' + rsp.ExpireIn)
        api.success({ key: 'kingDEVICE', message: '接警成功', placement: 'topLeft' })
    } catch (error) {
        console.error('接警失败', error)
        api.error({ key: 'kingDEVICE', message: '接警失败', placement: 'topLeft' })
    }
}

// 结束接警
export const deviceAlarmDone = async (sdk, alarmTaskObject, api) => {
    api.info({ key: 'kingDEVICE', message: '结束接警...', placement: 'topLeft' })
    try {
        await sdk.deviceAlarmDone(alarmTaskObject)
        console.log('结束接警成功')
        api.success({ key: 'kingDEVICE', message: '结束接警成功', placement: 'topLeft' })
    } catch (error) {
        console.error('结束接警失败', error)
        api.error({ key: 'kingDEVICE', message: '结束接警失败', placement: 'topLeft' })
    }
}
